package cn.s1995.sloth.bizs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.s1995.sloth.app.api.feign.RemoteAppUserService;
import cn.s1995.sloth.app.api.vo.AppUserVO;
import cn.s1995.sloth.bizs.constant.BizCst;
import cn.s1995.sloth.bizs.entity.Message;
import cn.s1995.sloth.bizs.entity.MessageTemplate;
import cn.s1995.sloth.bizs.entity.Order;
import cn.s1995.sloth.bizs.enums.NotifyTemplateEnum;
import cn.s1995.sloth.bizs.mapper.MessageMapper;
import cn.s1995.sloth.bizs.mapper.VideoCommentMapper;
import cn.s1995.sloth.bizs.oo.req.MessageREQ;
import cn.s1995.sloth.bizs.oo.vo.MessageVO;
import cn.s1995.sloth.bizs.service.MessageService;
import cn.s1995.sloth.bizs.service.MessageTemplateService;
import cn.s1995.sloth.bizs.service.OrderItemService;
import cn.s1995.sloth.bizs.service.OrderService;
import cn.s1995.sloth.common.core.util.R;
import cn.s1995.sloth.common.security.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * 消息
 *
 * @author sloth
 * @date 2024-01-06 10:01:34
 */
@Slf4j
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

	@Resource
	private OrderService orderService;
	@Resource
	private MessageTemplateService messageTemplateService;
	@Resource
	private OrderItemService orderItemService;
	@Resource
	private VideoCommentMapper videoCommentMapper;
	@Resource
	private RemoteAppUserService appUserService;

	@Override
	public Page getReceivePage(Page page, MessageREQ req) {
        LambdaQueryWrapper<Message> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Message::getToId, SecurityUtils.getUser().getId());
        wrapper.eq(ObjectUtil.isNotNull(req.getType()), Message::getType, req.getType());
        wrapper.eq(ObjectUtil.isNotNull(req.getHasRead()), Message::getHasRead, req.getHasRead());
        wrapper.orderByDesc(Message::getCreateTime);
		Page<Message> resultPage = this.page(page, wrapper);
		List<Message> records = resultPage.getRecords();
		if(ObjectUtil.isNotEmpty(records)) {
			for (int i = 0; i < records.size(); i++) {
				Message message = records.get(i);
				MessageVO vo = BeanUtil.copyProperties(message, MessageVO.class);
				//查询对应的数据
				if(ObjectUtil.isNotNull(vo.getBindId())) {
					switch (vo.getBindType()) {
					case BizCst.Message.BindType.order:
						Order order = orderService.getById(vo.getBindId());
						if(ObjectUtil.isNotNull(order))
							order.setOrderItems(orderItemService.getOrderItemsByOrderId(vo.getBindId()));
						vo.setBindData(order);
						break;
					case BizCst.Message.BindType.videoComment:
						vo.setBindData(videoCommentMapper.selectById(vo.getBindId()));
						break;
					default:
						break;
					}
				}
				records.set(i, vo);
			}
		}
		return resultPage;
	}

	@Override
	@Async
	public void sendOrderMessage(int template, Long orderId, Long uid) {
		try {
			this.save(
				Message.builder()
					   .fromId(0L)
					   .toId(uid)
					   .type(BizCst.Message.Type.order)
					   .state(0)
					   .title(BizCst.Message.Template.getTemplateStr(template))
					   .content(BizCst.Message.Template.getTemplateStr(template))
					   .bindId(orderId)
					   .bindType(BizCst.Message.BindType.order)
					   .build()
			);
		} catch (Exception e) {
			return;
		}
	}

	@Override
	@Async
	public void sendMsgForOrder(NotifyTemplateEnum messageEnum, Long orderId, Long uid) {
		this.save(
				Message.builder()
						.fromId(0L)
						.toId(uid)
						.state(0)
						.type(BizCst.Message.Type.order)
						.bindType(BizCst.Message.BindType.order)
						.bindId(orderId)
						.title(messageEnum.getContent())
						.content(messageEnum.getContent())

						.build()
		);
	}

	@Override
	@Async
	public void sendMsgForVideo(NotifyTemplateEnum messageEnum, Long uid, Long orderId) {
		this.save(
				Message.builder()
						.fromId(0L)
						.toId(uid)
						.state(0)
						.type(BizCst.Message.Type.system)
						.bindType(BizCst.Message.BindType.videoComment)
						.bindId(orderId)
						.title(messageEnum.getContent())
						.content(messageEnum.getContent())

						.build()
		);
	}

	@Override
	public void sendMsg(Long templateId, Long fromId, Long toId, Integer type, Integer bindType, Long bindId, Object... args) {
		MessageTemplate template = messageTemplateService.getById(templateId);
		if(ObjectUtil.isNotNull(template)) {
			//获取用户语言
			R<AppUserVO> res = appUserService.getById(toId);
			String lang = null;
			if(ObjectUtil.isNotNull(res.getData())) {
				lang = res.getData().getLang();
			}
			this.save(
					Message.builder()
							.fromId(fromId)
							.toId(toId)
							.state(0)
							.type(type)
							.bindType(bindType)
							.bindId(bindId)
							.title(template.getTitle().langFormat(lang))
							.content(template.getContent().langFormat(lang, args))
							.build()
			);
		}
	}

	@Override
	public void readBatch(List<Long> ids) {
		this.update(
			Wrappers.lambdaUpdate(Message.class)
					.set(Message::getHasRead, true)
					.in(Message::getId, ids)
		);
	}
}
